import axios from 'axios';
import { saveAs } from 'file-saver';
import JSZip from 'jszip';

export const getFile = (url: string) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        responseType: 'arraybuffer',
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.toString());
      });
  });
};
export const downloadZipImages = (
  list: Array<{ image_url: string; image_name: string }>
) => {
  // 创建JSZip实例
  const zip = new JSZip();
  // promise对象
  const promises: Promise<any>[] = [];

  list.forEach(({ image_url, image_name }) => {
    // 生成promise实例
    // api/v1/images/3b2616af-4095-4383-a847-2c11d7965b59.png/full
    const promise = getFile(image_url).then((res: any) => {
      zip.file(image_name, res);
    });
    promises.push(promise);
  });

  Promise.all(promises).then(() => {
    // 生成二进制流
    zip
      .generateAsync({
        type: 'blob',
      })
      .then((content) => {
        saveAs(content, 'Images.zip');
        /* 保存文件 */
      });
  });
};
